package com.itheima.health.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.health.common.Result;
import com.itheima.health.pojo.LoginDto;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author cfr
 * @date 2022/1/3
 * @TIME:19:57
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private MemberService memberService;

    @PostMapping("/login.do")
    public Result login(@RequestBody LoginDto loginDto) {
        if (loginDto == null) {
            return new Result(false, "参数错误");
        }
        String code = (String) request.getSession().getAttribute(loginDto.getTelephone());
        if (code == null) {
            return new Result(false, "请输入正确的手机号");
        }
        if (!loginDto.getValidateCode().equals(code)) {
            return new Result(false, "验证码不正确");
        }
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getPhoneNumber, loginDto.getTelephone());
        Member member = memberService.getOne(wrapper);
        if (member==null) {
            Member member1 = new Member();
            member1.setPhoneNumber(loginDto.getTelephone());
            member1.setRegTime(new Date());
            memberService.save(member1);
            request.getSession().setAttribute("member", member1.getId());
            return new Result(true, "登录成功");
        }
        request.getSession().setAttribute("member", member.getId());
        return new Result(true, "登录成功");
    }
}
